package cache

import "time"

type Scheduler struct {
	interval      time.Duration
	expiryManager *ExpiryManager
	cleanupTimer  *time.Timer
}

func NewScheduler(interval time.Duration, expiryManager *ExpiryManager) *Scheduler {
	return &Scheduler{
		interval:      interval,
		expiryManager: expiryManager,
	}
}

func (scheduler *Scheduler) Start() {
	nextDuration := scheduler.expiryManager.deleteExpired()
	if scheduler.cleanupTimer != nil {
		scheduler.cleanupTimer.Stop()
	}

	scheduler.interval = nextDuration

	if nextDuration > 0 {
		scheduler.cleanupTimer = time.AfterFunc(nextDuration, scheduler.Start)
	}

}

func (scheduler *Scheduler) Stop() {
	if scheduler.cleanupTimer != nil {
		scheduler.cleanupTimer.Stop()
	}
}
